/**
 *  Copyright (c) 2014 The xmlepf project.  All rights reserved.
 *
 *  This file is part of xmlepf (Event Driven Testing Framework).
 *
 *  xmlepf is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  xmlepf is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with xmlepf.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  This software consists of voluntary contributions made by many
 *  individuals.  For exact contribution history, see the revision
 *  history and logs, available at http://code.google.com/p/xmlepf.
 */
package org.xmlepf.xtemp.functions;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.Item;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.om.SequenceIterator;
import net.sf.saxon.tree.iter.SingleNodeIterator;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.SequenceType;
import org.xmlepf.utils.ObjectCreator;
import org.xmlepf.utils.Sys;
import org.xmlepf.xml.adapter.NodeSerializer;
import org.xmlepf.xml.adapter.XMLNode;
import org.xmlepf.xml.adapter.XMLTypeConvertor;
import org.xmlepf.xtemp.event.Event;
import org.xmlepf.xtemp.script.ExecutionContext;
import org.xmlepf.xtemp.event.EventManager;

/**
 *
 *
 */
public class QueryBoard extends ExtensionFunctionDefinition {

    private static final String queryBoardLocalName = "query-board";
    private static final String queryBoardPrefix = "xtemp";
    private static final String queryBoardNameSpace =
            "http://docs.oasis-open.org/tamie/xtemp/200909";
    private static StructuredQName functionName =
            new StructuredQName(queryBoardPrefix, queryBoardNameSpace, queryBoardLocalName);
    private static SequenceType[] argumentTypes = new SequenceType[]{
        SequenceType.OPTIONAL_STRING, // 0. The board name
        SequenceType.OPTIONAL_STRING, // 1. The condition
        SequenceType.OPTIONAL_STRING, // 2. The XPath expression (above condition will be inserted)
        SequenceType.SINGLE_BOOLEAN, // 3. If true, return all events mathing the XPath expression.
        //    If false, return only the first event matching the XPath expression.
        SequenceType.OPTIONAL_STRING}; // 4. catch/@tryfor, in the ISO 8601 format ([+|-]PnDTnHnMnS)
    private ExecutionContext executionContext;

    public QueryBoard(ExecutionContext executionContext) {
        this.executionContext = executionContext;
    }

    @Override
    public StructuredQName getFunctionQName() {
        return functionName;
    }

    @Override
    public int getMinimumNumberOfArguments() {
        return 5;
    }

    @Override
    public int getMaximumNumberOfArguments() {
        return 5;
    }

    @Override
    public SequenceType[] getArgumentTypes() {
        return argumentTypes;
    }

    @Override
    public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
        return SequenceType.NODE_SEQUENCE;
    }

    @Override
    public ExtensionFunctionCall makeCallExpression() {
        return new QueryBoardCall(executionContext);
    }

    private class QueryBoardCall extends ExtensionFunctionCall {

        private ExecutionContext executionContext;
        private EventManager eventManager;

        public QueryBoardCall(ExecutionContext executionContext) {
            this.executionContext = executionContext;
            eventManager = executionContext.getEventManager();
        }

        @Override
        public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException {

            NodeInfo outputNode = null;
            String boardName = "";
            String boardQuery = "";
            boolean shouldIdentifyAllEventsMatchingThisQuery = false;
            NodeSerializer s = null;

            try {
                s = (NodeSerializer) ObjectCreator.get("NodeSerializer");

                // retrieve the board name, if any
                boardName = executionContext.getDefaultBoardName();
                Item boardNameArg = arguments[0].next();
                if (boardNameArg != null && !boardNameArg.getStringValue().isEmpty()) {
                    boardName = boardNameArg.getStringValue();
                }

                // retrieve the compound condition
                Item compoundConditionArg = arguments[1].next();
                String compoundCondition = "";
                if (compoundConditionArg != null) {
                    compoundCondition = compoundConditionArg.getStringValue();
                }

                // retrieve the board query and replace the "compound-condition" with the actual query
                Item boardQueryArg = arguments[2].next();
                if (boardQueryArg != null) {
                    boardQuery = boardQueryArg.getStringValue();
                    if (!compoundCondition.isEmpty()) {
                        boardQuery = boardQuery.replaceAll("compound-condition", compoundCondition);
                    }
                }

                // todo: follow-up with OASIS TaMIE on how to treat an empty query. 
                // Until then, don't allow it (if needed, move this to XSLT after clarification):
                assert boardQuery.isEmpty() : "An empty query does not make sense. Please specify a query in your /catch/match/condition.";

                // retrieve the board query type
                Item boardQueryTypeArg = arguments[3].next();
                if (boardQueryArg != null) {
                    String shouldFindAllEvents = boardQueryTypeArg.getStringValue();
                    if (shouldFindAllEvents.equals("true")) {
                        shouldIdentifyAllEventsMatchingThisQuery = true;
                    }
                }

                
                // retrieve the query timeout (i.e. catch/@tryfor)
                XMLTypeConvertor xmlConvertor = (XMLTypeConvertor) ObjectCreator.get("XMLTypeConvertor");
                long catchMaxTimeout = xmlConvertor.xsdDayTimeDurationISO8601ToMilliseconds("P365D"); // initialize it with a long duration
                Item catchTryForTimeoutArg = arguments[4].next();
                if (catchTryForTimeoutArg != null) {
                    String timeout = catchTryForTimeoutArg.getStringValue();
                    if (!timeout.isEmpty()) {
                        catchMaxTimeout = xmlConvertor.xsdDayTimeDurationISO8601ToMilliseconds(timeout);
                    }
                }
                String timeoutInISO8601Format = xmlConvertor.millisecondsToXsdDayTimeDurationISO8601(catchMaxTimeout);

                // todo: follow-up with OASIS TaMIE on how to treat a negative duration. 
                // Until then, don't allow it (if needed, move this to xslt after clarification):
                assert catchMaxTimeout > 0 : "The query timeout '" + timeoutInISO8601Format
                        + "' specified through @tryfor cannot be negative. Please specify a positive duration.";

                List<Event> matchedEvents = new LinkedList<Event>();
                if (shouldIdentifyAllEventsMatchingThisQuery) {
                    Logger.getLogger(QueryBoard.class.getName()).log(Level.INFO,
                            "QueryBoard: querying event board ''{0}'' for events using query ''{1}'' and a timeout of ''{2}''.",
                            new Object[]{boardName, boardQuery, timeoutInISO8601Format});

                    matchedEvents = eventManager.catchEvents(boardName, boardQuery, catchMaxTimeout);
                } else {
                    Logger.getLogger(QueryBoard.class.getName()).log(Level.INFO,
                            "QueryBoard: querying event board ''{0}'' for an event using query ''{1}'' and a timeout of ''{2}''.",
                            new Object[]{boardName, boardQuery, timeoutInISO8601Format});

                    matchedEvents.add(eventManager.catchEvent(boardName, boardQuery, catchMaxTimeout));
                }

                String serializedEvent = eventManager.serialize(matchedEvents);
                XMLNode xmlNode = s.deserialize(serializedEvent, context.getConfiguration());
                outputNode = (NodeInfo) xmlNode.getNativeNode();

                // todo: complete implementation
                //outputNode = eventManager.mergeEvents(matchedEvents, context.getConfiguration());

                //String serializedEvents = s.serialize(outputNode );
                //Logger.getLogger(QueryBoard.class.getName()).log(Level.INFO, "QueryBoard: returning this event to the transformation:\n''{0}''", serializedEvent);
            } catch (Exception ex) {
                Logger.getLogger(QueryBoard.class.getName()).log(Level.WARNING,
                        "QueryBoard: while querying event board ''{0}'' using query ''{1}'', the following exception was encountered:\n''{2}''",
                        new Object[]{boardName, boardQuery, ex});
                Logger.getLogger(QueryBoard.class.getName()).log(Level.FINER,
                        "\nStack trace for the above exception:\n''{1}''",
                        new Object[]{Sys.getStackTraceAsString(ex)});
            }
            
//            if ( outputNode == null ) {
//                try {
//                    outputNode = s.deserialize( "<no-more-events/>", context.getConfiguration());
//                } catch( Exception ex ) {
//                }
//            }
            
            return SingleNodeIterator.makeIterator(outputNode);
        }
    }
}
